package org.jim.server.command.handler;

import org.jim.common.*;
import org.jim.common.cache.redis.JedisTemplate;
import org.jim.common.cache.redis.RedisCache;
import org.jim.common.cache.redis.RedisCacheManager;
import org.jim.common.packets.*;
import org.jim.common.utils.ImKit;
import org.jim.server.command.AbstractCmdHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;

import java.util.Date;

/**
 *
 */
public class HeartbeatReqHandler extends AbstractCmdHandler {

    RedisCache HeartCache = new RedisCache(ImConst.HEART, 5000, 10000);

    @Override
    public ImPacket handler(ImPacket packet, ChannelContext channelContext) throws Exception {

        RespBody heartbeatBody = new RespBody(Command.COMMAND_HEARTBEAT_REQ).setData(new HeartbeatBody(Protocol.HEARTBEAT_BYTE));

        ImPacket heartbeatPacket = ImKit.ConvertRespPacket(heartbeatBody, channelContext);
        ImSessionContext imSessionContext = (ImSessionContext) channelContext.getAttribute();
        Client client = imSessionContext.getClient();
        User user = client.getUser();
        if (user == null) {
            RespBody respBody = new RespBody(Command.COMMAND_LOGIN_RESP, ImStatus.C10047);
            heartbeatPacket = new ImPacket(Command.COMMAND_LOGIN_RESP, respBody.toByte());
            return heartbeatPacket;
        }

        HeartCache.hashSet("user", user.getId(), String.valueOf(new Date().getTime()));
        return heartbeatPacket;
    }

    @Override
    public Command command() {
        return Command.COMMAND_HEARTBEAT_REQ;
    }
}
